var express = require('express');
var router = express.Router();
var $sql = require('../db/sqlMap');
const sqlite3 = require('sqlite3').verbose();



var jsonWrite = function(res, ret) {
    if(typeof ret === 'undefined') {
        res.send('err');
    } else {
        console.log(ret);
        res.setHeader('Content-Type','text/plain; charset=utf-8');
        res.send(ret);
    }
}

var dateStr = function(str) {
    return new Date(str.slice(0,7));
}

// add user
router.post('/addSite', (req, res) => {
    let db = new sqlite3.Database('./db/IIs.s3db', (err) => {
    if (err) {
        console.error(err.message);
    }
        console.log('Connected to the database.');
    });
    
    var sql = $sql.site.add;
    var params = req.body;
    console.log(params);
    sql=sql+' '+'(\''+params.Id+'\',\''+params.sitename+'\',\''+params.address+'\',\''+params.inform1name+'\',\''+params.inform1phone+'\',\''+params.inform2name+'\',\''+params.inform2phone+'\',\''+params.UserIdId+'\')';
    console.log(sql)
    db.get(sql, function(err, result) {
        if (err) {
            console.log(err);
        }
        else{
            res.send('ok');
        }
    })
    db.close();
});


//search user
router.post('/show', (req, res) => {
    let db = new sqlite3.Database('./db/IIs.s3db', (err) => {
    if (err) {
        console.error("!!!!")
        console.error(err.message);
    }
        console.log('Connected to the database.');
    });
    var sql_account = $sql.site.select_sites;
    var params = req.body;
    var keywords = JSON.parse(Object.keys(params));
    if (keywords.account) {
        sql_account += " where UserId ='"+ keywords.account +"'";
    }
    db.all(sql_account, function(err, result) {
        if (err) {
            console.log(err);
        }
        if (result === undefined) {
            res.send('-1')   //cannot search username，return -1
        } else {
            jsonWrite(res, result);
            console.log("我的")
        }
    })
    db.close();
});


module.exports = router;
